// MQTT服务管理器
// 提供统一的MQTT功能接口，简化渲染进程的使用

interface AppInfoResponse {
  code: number
  msg: string
  appName: string
  appVersion: string
}

interface WarnStatusResponse {
  code: number
  msg: string
  data: Array<{
    time: string
    identification: string
    content: string
  }>
}

interface WorkFlowStatusResponse {
  code: number
  msg: string
  data: Array<{
    time: string
    flowId: string
    flowSend: string
    flowRecv: string
    subject: string
    content: string
  }>
}

interface MQTTStatus {
  isInitialized: boolean
  isConnected: boolean
  isAvailable: boolean
}

interface MQTTConfig {
  brokerUrl: string
  username: string
  password: string
  clientId: string
}

interface MQTTEventCallbacks {
  onConnect?: () => void
  onDisconnect?: () => void
  onError?: (error: string) => void
  onAppInfoUpdate?: (appInfo: AppInfoResponse) => void
  onWarnStatusUpdate?: (warnStatus: WarnStatusResponse) => void
  onWorkFlowStatusUpdate?: (workFlowStatus: WorkFlowStatusResponse) => void
  onStatusChange?: (status: MQTTStatus) => void
}

class MQTTManager {
  private static instance: MQTTManager | null = null
  private currentStatus: MQTTStatus = { isInitialized: false, isConnected: false, isAvailable: false }
  private eventCallbacks: MQTTEventCallbacks = {}
  private statusCheckInterval: NodeJS.Timeout | null = null

  private constructor() {
    this.setupEventListeners()
  }

  static getInstance(): MQTTManager {
    if (!MQTTManager.instance) {
      MQTTManager.instance = new MQTTManager()
    }
    return MQTTManager.instance
  }

  private setupEventListeners(): void {
    // 监听主进程发送的应用信息更新
    if (window.api?.mqtt?.onAppInfoUpdate) {
      window.api.mqtt.onAppInfoUpdate((appInfo: AppInfoResponse) => {
        this.handleAppInfoUpdate(appInfo)
      })
    }

    // 监听主进程发送的警告状态更新
    if (window.api?.mqtt?.onWarnStatusUpdate) {
      window.api.mqtt.onWarnStatusUpdate((warnStatus: WarnStatusResponse) => {
        this.handleWarnStatusUpdate(warnStatus)
      })
    }
  }

  private handleAppInfoUpdate(appInfo: AppInfoResponse): void {
    console.log('收到应用信息更新:', appInfo)
    if (this.eventCallbacks.onAppInfoUpdate) {
      this.eventCallbacks.onAppInfoUpdate(appInfo)
    }
  }

  private handleWarnStatusUpdate(warnStatus: WarnStatusResponse): void {
    console.log('收到警告状态更新:', warnStatus)
    if (this.eventCallbacks.onWarnStatusUpdate) {
      this.eventCallbacks.onWarnStatusUpdate(warnStatus)
    }
  }

  private handleWorkFlowStatusUpdate(workFlowStatus: WorkFlowStatusResponse): void {
    console.log('收到工作流程状态更新:', workFlowStatus)
    if (this.eventCallbacks.onWorkFlowStatusUpdate) {
      this.eventCallbacks.onWorkFlowStatusUpdate(workFlowStatus)
    }
  }

  private async handleStatusChange(): Promise<void> {
    try {
      const newStatus = await this.getStatus()
      if (JSON.stringify(newStatus) !== JSON.stringify(this.currentStatus)) {
        this.currentStatus = newStatus
        if (this.eventCallbacks.onStatusChange) {
          this.eventCallbacks.onStatusChange(newStatus)
        }
      }
    } catch (error) {
      console.error('获取状态失败:', error)
    }
  }

  async connect(config: MQTTConfig): Promise<{ success: boolean; error?: string }> {
    try {
      console.log('开始连接MQTT:', config.brokerUrl)
      
      const result = await window.api?.mqtt?.initialize(
        config.brokerUrl,
        config.username,
        config.password,
        config.clientId
      )

      if (result?.success) {
        if (this.eventCallbacks.onConnect) {
          this.eventCallbacks.onConnect()
        }
        this.startStatusMonitoring()
        return { success: true }
      } else {
        const error = result?.error || '连接失败'
        if (this.eventCallbacks.onError) {
          this.eventCallbacks.onError(error)
        }
        return { success: false, error }
      }
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '连接异常'
      if (this.eventCallbacks.onError) {
        this.eventCallbacks.onError(errorMessage)
      }
      return { success: false, error: errorMessage }
    }
  }

  async disconnect(): Promise<{ success: boolean }> {
    try {
      const result = await window.api?.mqtt?.disconnect()
      this.stopStatusMonitoring()
      
      if (this.eventCallbacks.onDisconnect) {
        this.eventCallbacks.onDisconnect()
      }
      
      return { success: result?.success || false }
    } catch (error) {
      console.error('断开连接失败:', error)
      return { success: false }
    }
  }

  async reconnect(): Promise<{ success: boolean; error?: string }> {
    try {
      const result = await window.api?.mqtt?.reconnect()
      return { success: result?.success || false, error: result?.error }
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '重连异常'
      return { success: false, error: errorMessage }
    }
  }

  async getStatus(): Promise<MQTTStatus> {
    try {
      const status = await window.api?.mqtt?.getStatus()
      return status || { isInitialized: false, isConnected: false, isAvailable: false }
    } catch (error) {
      console.error('获取状态失败:', error)
      return { isInitialized: false, isConnected: false, isAvailable: false }
    }
  }

  async getAppInfo(): Promise<AppInfoResponse | null> {
    try {
      const appInfo = await window.api?.mqtt?.getAppInfo()
      return appInfo || null
    } catch (error) {
      console.error('获取应用信息失败:', error)
      return null
    }
  }

  async requestAppInfo(): Promise<{ success: boolean }> {
    try {
      const result = await window.api?.mqtt?.requestAppInfo()
      return { success: result?.success || false }
    } catch (error) {
      console.error('请求应用信息失败:', error)
      return { success: false }
    }
  }

  async getWarnStatus(): Promise<WarnStatusResponse | null> {
    try {
      const warnStatus = await window.api?.mqtt?.getWarnStatus?.()
      return warnStatus || null
    } catch (error) {
      console.error('获取警告状态失败:', error)
      return null
    }
  }

  async requestWarnStatus(): Promise<{ success: boolean }> {
    try {
      const result = await window.api?.mqtt?.requestWarnStatus?.()
      return { success: result?.success || false }
    } catch (error) {
      console.error('请求警告状态失败:', error)
      return { success: false }
    }
  }

  setEventCallbacks(callbacks: MQTTEventCallbacks): void {
    this.eventCallbacks = { ...this.eventCallbacks, ...callbacks }
  }

  removeEventCallbacks(): void {
    this.eventCallbacks = {}
  }

  private startStatusMonitoring(): void {
    if (this.statusCheckInterval) {
      clearInterval(this.statusCheckInterval)
    }
    
    this.statusCheckInterval = setInterval(() => {
      this.handleStatusChange()
    }, 2000) // 每2秒检查一次状态
  }

  private stopStatusMonitoring(): void {
    if (this.statusCheckInterval) {
      clearInterval(this.statusCheckInterval)
      this.statusCheckInterval = null
    }
  }

  async isConnected(): Promise<boolean> {
    const status = await this.getStatus()
    return status.isConnected
  }

  async isAvailable(): Promise<boolean> {
    const status = await this.getStatus()
    return status.isAvailable
  }

  cleanup(): void {
    this.stopStatusMonitoring()
    this.removeEventCallbacks()
    if (window.api?.mqtt?.removeAppInfoUpdateListener) {
      window.api.mqtt.removeAppInfoUpdateListener()
    }
    if (window.api?.mqtt?.removeWarnStatusUpdateListener) {
      window.api.mqtt.removeWarnStatusUpdateListener()
    }
  }
}

const mqttManager = MQTTManager.getInstance()
export default mqttManager
export type { AppInfoResponse, WarnStatusResponse, WorkFlowStatusResponse, MQTTStatus, MQTTConfig, MQTTEventCallbacks }
